package com.yunxin.core.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.Result;
import com.yunxin.core.admin.domain.AdminUser;
import com.yunxin.core.admin.mapper.AdminUserMapper;
import com.yunxin.core.admin.service.AdminUserService;
import com.yunxin.core.application.assembler.OrderAssembler;
import com.yunxin.core.application.dto.order.OrderUserApplyDetailDTO;
import com.yunxin.core.application.service.TeamService;
import com.yunxin.core.customer.domain.*;
import com.yunxin.core.customer.dto.*;
import com.yunxin.core.customer.mapper.CustomerTagMapper;
import com.yunxin.core.customer.service.*;
import com.yunxin.core.customer.mapper.CustomerInfoMapper;
import com.yunxin.core.customer.vo.*;
import com.yunxin.core.domain.model.team.Team;
import com.yunxin.core.utils.infra.common.enums.AccumulationFundLevelEnum;
import com.yunxin.core.utils.infra.common.enums.SocialSecurityLevelEnum;
import com.yunxin.core.wechat.domain.WechatFollowCustomer;
import com.yunxin.core.wechat.domain.WechatTagInfo;
import com.yunxin.core.wechat.mapper.WechatTagInfoMapper;
import com.yunxin.core.wechat.service.WechatFollowCustomerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Administrator
 * @description 针对表【customer_info(客户信息详情表)】的数据库操作Service实现
 * @createDate 2024-05-22 17:11:04
 */
@DS("crm")
@Service
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private CustomerTagMapper customerTagMapper;

    @Autowired
    private TagInfoService tagInfoService;

    @Autowired
    private CustomerInfoDetailService customerInfoDetailService;

    @Autowired
    private OrderAssembler orderAssembler;

    @Autowired
    private CustomerTagService customerTagService;

    @Autowired
    @Lazy
    private WechatFollowCustomerService wechatFollowCustomerService;

    @Autowired
    private WechatTagInfoMapper wechatTagInfoMapper;

    @Autowired
    private CustomerShipAllocationService customerShipAllocationService;

    @Autowired
    private CustomerMatchingProductService customerMatchingProductService;

    @Autowired
    private MatchingProductService matchingProductService;
    @Autowired
    @Lazy
    private TeamService teamService;
    @Autowired
    private CustomerOperationLogService customerOperationLogService;

    @Autowired
    @Lazy
    private CustomerTelephonerLogService customerTelephonerLogService;

    @Override
    public IPage<CustomerInfoVo> customerPageQuery(CustomerPageDto command) {
        CustomerCommonPageDto pageDto = new CustomerCommonPageDto();
        BeanUtil.copyProperties(command, pageDto);
        // 商户管理员数据
        IPage<CustomerCommonVo> iPage = listAllCustomerInfo(pageDto);
        if (CollUtil.isEmpty(iPage.getRecords())) {
            return new Page<>();
        }
        List<CustomerCommonVo> records = iPage.getRecords();
        Map<Long,List<CustomerMatchingProduct>> cmpMap=new HashMap<>();
        Map<Long,List<Long>> customerTagMap=new HashMap<>();
        Map<Long, String> tagMap = new HashMap<>();
        Map<String, String> wechatTagMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(records)){
            List<Integer> customerIds = records.stream().map(i -> i.getCustomerId()).toList();
            //客户分配产品
            List<Integer> wechatCustomerIds = records.stream().map(i -> i.getWechatCustomerId()).toList();
            LambdaQueryWrapper<CustomerMatchingProduct> matchingProductLambdaQueryWrapper=new LambdaQueryWrapper<>();
            matchingProductLambdaQueryWrapper.in(CustomerMatchingProduct::getWechatCustomerId,wechatCustomerIds);
            List<CustomerMatchingProduct> matchingProducts = customerMatchingProductService.list(matchingProductLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(matchingProducts)){
                Set<Long> mpIds = matchingProducts.stream().map(i -> i.getMatchingProductId()).collect(Collectors.toSet());
                List<MatchingProduct> matchingProductList = matchingProductService.listByIds(mpIds);
                Map<Integer, String> mpMap = matchingProductList.stream().collect(Collectors.toMap(MatchingProduct::getId, obj -> obj.getName()));
                for (CustomerMatchingProduct matchingProduct : matchingProducts) {
                    List<CustomerMatchingProduct> customerMatchingProducts = cmpMap.get(matchingProduct.getWechatCustomerId());
                    if (ObjectUtils.isEmpty(customerMatchingProducts)){
                        customerMatchingProducts = new ArrayList<>();
                        cmpMap.put(matchingProduct.getWechatCustomerId(),customerMatchingProducts);
                    }
                    if(StringUtils.isNotBlank(mpMap.get(matchingProduct.getMatchingProductId().intValue()))){
                        matchingProduct.setMatchingProductName(mpMap.get(matchingProduct.getMatchingProductId().intValue()));
                        customerMatchingProducts.add(matchingProduct);
                    }
                }
            }

            //系统标签
            LambdaQueryWrapper<CustomerTag> customerTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            customerTagLambdaQueryWrapper.in(CustomerTag::getCustomerInfoId,customerIds);
            List<CustomerTag> customerTagList = customerTagService.list(customerTagLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(customerTagList) && !customerTagList.isEmpty()){
                for (CustomerTag customerTag : customerTagList) {
                    List<Long> tagIdList = customerTagMap.get(customerTag.getCustomerInfoId());
                    if (ObjectUtils.isEmpty(tagIdList)){
                        tagIdList=new ArrayList<>();
                    }
                    tagIdList.add(customerTag.getTagInfoId());
                    customerTagMap.put(customerTag.getCustomerInfoId(),tagIdList);
                }
                Set<Long> tagInfoIds = customerTagList.stream().map(i -> i.getTagInfoId()).collect(Collectors.toSet());
                List<TagInfo> tagInfoList = tagInfoService.listByIds(tagInfoIds);
                Map<Long, String> tagNameMap = tagInfoList.stream().collect(Collectors.toMap(TagInfo::getId, obj -> obj.getName()));
                tagMap.putAll(tagNameMap);
            }
            //企微标签
            if (!ObjectUtils.isEmpty(wechatCustomerIds)&&wechatCustomerIds.size()>0){
                Set<String> wechatTagIds=new HashSet<>();
                for (CustomerCommonVo record : records) {
                    if (!ObjectUtils.isEmpty(record.getWechatTagIds())){
                        wechatTagIds.addAll(JSON.parseArray(record.getWechatTagIds().toString(), String.class));
                    }
                }
                if (wechatTagIds.size()>0){
                    LambdaQueryWrapper<WechatTagInfo> tagInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
                    tagInfoLambdaQueryWrapper.in(WechatTagInfo::getTagId,wechatTagIds);
                    List<WechatTagInfo> wechatTagInfos = wechatTagInfoMapper.selectList(tagInfoLambdaQueryWrapper);
                    Map<String, String> collect1 = wechatTagInfos.stream().collect(Collectors.toMap(WechatTagInfo::getTagId, obj -> obj.getTagName()));
                    wechatTagMap.putAll(collect1);
                }
            }


        }
        return iPage.convert(x -> {
            CustomerInfoVo vo = new CustomerInfoVo();
            BeanUtil.copyProperties(x, vo);
            if (!ObjectUtils.isEmpty(x.getWechatCustomerId())){
                vo.setCustomerMatchingProducts(cmpMap.get(x.getWechatCustomerId().longValue()));
            }
            //系统标签
            List<Long> tagIds = customerTagMap.get(x.getCustomerId().longValue());
            if (!ObjectUtils.isEmpty(tagIds)&&!tagIds.isEmpty()){
                List<String> sysTags=new ArrayList<>();
                for (Long tagId : tagIds) {
                    String tagName = tagMap.get(tagId);
                    if (!ObjectUtils.isEmpty(tagName)){
                        sysTags.add(tagName);
                    }
                }
                vo.setSysTags(sysTags);
            }
            //企微标签
            if (!ObjectUtils.isEmpty(x.getWechatTagIds())){
                List<String> wechatTags=new ArrayList<>();
                List<String> wechatTagIds = JSON.parseArray(x.getWechatTagIds().toString(), String.class);
                for (String wechatTagId : wechatTagIds) {
                    String wechatTagName = wechatTagMap.get(wechatTagId);
                    if (StringUtils.isNotBlank(wechatTagName)){
                        wechatTags.add(wechatTagName);
                    }
                }
                vo.setWechatTags(wechatTags);
            }
            return vo;
        });
    }

    @Override
    public IPage<CustomerTelephoneInfoVo> customerTelephonerPageQuery(CustomerTelephonerPageDto command) {
        CustomerCommonPageDto pageDto = new CustomerCommonPageDto();
        BeanUtil.copyProperties(command, pageDto);
        if (!ObjectUtils.isEmpty(pageDto.getTeamId())){
            pageDto.setTeamIds(List.of(pageDto.getTeamId()));
        }
        IPage<CustomerCommonVo> iPage = listAllCustomerInfo(pageDto);
        if (CollUtil.isEmpty(iPage.getRecords())) {
            return new Page<>();
        }
        List<CustomerCommonVo> records = iPage.getRecords();
        Map<Long,List<Long>> customerTagMap=new HashMap<>();
        Map<Long, String> tagMap = new HashMap<>();
        Map<String, String> wechatTagMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(records)){
            List<Integer> customerIds = records.stream().map(i -> i.getCustomerId()).toList();

            //系统标签
            LambdaQueryWrapper<CustomerTag> customerTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            customerTagLambdaQueryWrapper.in(CustomerTag::getCustomerInfoId,customerIds);
            List<CustomerTag> customerTagList = customerTagService.list(customerTagLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(customerTagList) && !customerTagList.isEmpty()){
                for (CustomerTag customerTag : customerTagList) {
                    List<Long> tagIdList = customerTagMap.get(customerTag.getCustomerInfoId());
                    if (ObjectUtils.isEmpty(tagIdList)){
                        tagIdList=new ArrayList<>();
                    }
                    tagIdList.add(customerTag.getTagInfoId());
                    customerTagMap.put(customerTag.getCustomerInfoId(),tagIdList);
                }
                Set<Long> tagInfoIds = customerTagList.stream().map(i -> i.getTagInfoId()).collect(Collectors.toSet());
                List<TagInfo> tagInfoList = tagInfoService.listByIds(tagInfoIds);
                Map<Long, String> tagNameMap = tagInfoList.stream().collect(Collectors.toMap(TagInfo::getId, obj -> obj.getName()));
                tagMap.putAll(tagNameMap);
            }
            //企微标签
            List<Integer> wechatCustomerIds = records.stream().map(i -> i.getWechatCustomerId()).toList();
            if (!ObjectUtils.isEmpty(wechatCustomerIds)&&wechatCustomerIds.size()>0){
                Set<String> wechatTagIds=new HashSet<>();
                for (CustomerCommonVo record : records) {
                    if (!ObjectUtils.isEmpty(record.getWechatTagIds())){
                        wechatTagIds.addAll(JSON.parseArray(record.getWechatTagIds().toString(), String.class));
                    }
                }
                if (wechatTagIds.size()>0){
                    LambdaQueryWrapper<WechatTagInfo> tagInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
                    tagInfoLambdaQueryWrapper.in(WechatTagInfo::getTagId,wechatTagIds);
                    List<WechatTagInfo> wechatTagInfos = wechatTagInfoMapper.selectList(tagInfoLambdaQueryWrapper);
                    Map<String, String> collect1 = wechatTagInfos.stream().collect(Collectors.toMap(WechatTagInfo::getTagId, obj -> obj.getTagName()));
                    wechatTagMap.putAll(collect1);
                }
            }

        }
        return iPage.convert(x -> {
            CustomerTelephoneInfoVo vo = new CustomerTelephoneInfoVo();
            BeanUtil.copyProperties(x, vo);
            //系统标签
            List<Long> tagIds = customerTagMap.get(x.getCustomerId().longValue());
            StringBuilder tagNames = new StringBuilder();
            if (!ObjectUtils.isEmpty(tagIds)&&!tagIds.isEmpty()){
                List<String> sysTags=new ArrayList<>();
                for (Long tagId : tagIds) {
                    String tagName = tagMap.get(tagId);
                    if (StringUtils.isNotBlank(tagName)){
                        sysTags.add(tagName);
                    }
                }
                vo.setSysTags(sysTags);
            }
            //企微标签
            if (!ObjectUtils.isEmpty(x.getWechatTagIds())){
                List<String> wechatTagIds = JSON.parseArray(x.getWechatTagIds().toString(), String.class);
                List<String> wechatTags=new ArrayList<>();
                for (String wechatTagId : wechatTagIds) {
                    String wechatTagName = wechatTagMap.get(wechatTagId);
                    if (StringUtils.isNotBlank(wechatTagName)){
                        wechatTags.add(wechatTagName);
                    }
                }
                vo.setWechatTags(wechatTags);
            }
            return vo;
        });
    }

    @Override
    public IPage<CustomerSalesmanInfoVo> customerSalesmanPageQuery(CustomerSalesmanPageDto command) {
        CustomerCommonPageDto pageDto = new CustomerCommonPageDto();
        BeanUtil.copyProperties(command, pageDto);
        if (!ObjectUtils.isEmpty(pageDto.getTeamId())){
            pageDto.setTeamIds(List.of(pageDto.getTeamId()));
        }
        IPage<CustomerCommonVo> iPage = listAllCustomerInfo(pageDto);
        if (CollUtil.isEmpty(iPage.getRecords())) {
            return new Page<>();
        }
        List<CustomerCommonVo> records = iPage.getRecords();
        Map<Long,List<CustomerMatchingProduct>> cmpMap=new HashMap<>();
        Map<Long,List<Long>> customerTagMap=new HashMap<>();
        Map<Long, String> tagMap = new HashMap<>();
        Map<String, String> wechatTagMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(records)){
            List<Integer> customerIds = records.stream().map(i -> i.getCustomerId()).toList();
            //客户分配产品
            List<Integer> wechatCustomerIds = records.stream().map(i -> i.getWechatCustomerId()).toList();
            if (!ObjectUtils.isEmpty(wechatCustomerIds)&&wechatCustomerIds.size()>0){
                LambdaQueryWrapper<CustomerMatchingProduct> matchingProductLambdaQueryWrapper=new LambdaQueryWrapper<>();
                matchingProductLambdaQueryWrapper.in(CustomerMatchingProduct::getWechatCustomerId,wechatCustomerIds);
                List<CustomerMatchingProduct> matchingProducts = customerMatchingProductService.list(matchingProductLambdaQueryWrapper);
                if (!ObjectUtils.isEmpty(matchingProducts)){
                    Set<Long> mpIds = matchingProducts.stream().map(i -> i.getMatchingProductId()).collect(Collectors.toSet());
                    List<MatchingProduct> matchingProductList = matchingProductService.listByIds(mpIds);
                    Map<Integer, String> mpMap = matchingProductList.stream().collect(Collectors.toMap(MatchingProduct::getId, obj -> obj.getName()));
                    for (CustomerMatchingProduct matchingProduct : matchingProducts) {
                        List<CustomerMatchingProduct> customerMatchingProducts = cmpMap.get(matchingProduct.getCustomerId());
                        if (ObjectUtils.isEmpty(customerMatchingProducts)){
                            customerMatchingProducts = new ArrayList<>();
                            cmpMap.put(matchingProduct.getWechatCustomerId(),customerMatchingProducts);
                        }
                        if(StringUtils.isNotBlank(mpMap.get(matchingProduct.getMatchingProductId().intValue()))){
                            matchingProduct.setMatchingProductName(mpMap.get(matchingProduct.getMatchingProductId().intValue()));
                            customerMatchingProducts.add(matchingProduct);
                        }
                    }
                }
            }


            //系统标签
            LambdaQueryWrapper<CustomerTag> customerTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            customerTagLambdaQueryWrapper.in(CustomerTag::getCustomerInfoId,customerIds);
            List<CustomerTag> customerTagList = customerTagService.list(customerTagLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(customerTagList) && !customerTagList.isEmpty()){
                for (CustomerTag customerTag : customerTagList) {
                    List<Long> tagIdList = customerTagMap.get(customerTag.getCustomerInfoId());
                    if (ObjectUtils.isEmpty(tagIdList)){
                        tagIdList=new ArrayList<>();
                    }
                    tagIdList.add(customerTag.getTagInfoId());
                    customerTagMap.put(customerTag.getCustomerInfoId(),tagIdList);
                }
                Set<Long> tagInfoIds = customerTagList.stream().map(i -> i.getTagInfoId()).collect(Collectors.toSet());
                List<TagInfo> tagInfoList = tagInfoService.listByIds(tagInfoIds);
                Map<Long, String> tagNameMap = tagInfoList.stream().collect(Collectors.toMap(TagInfo::getId, obj -> obj.getName()));
                tagMap.putAll(tagNameMap);
            }
            //企微标签
            if (!ObjectUtils.isEmpty(wechatCustomerIds)&&wechatCustomerIds.size()>0){
                Set<String> wechatTagIds=new HashSet<>();
                for (CustomerCommonVo record : records) {
                    if (!ObjectUtils.isEmpty(record.getWechatTagIds())){
                        wechatTagIds.addAll(JSON.parseArray(record.getWechatTagIds().toString(), String.class));
                    }
                }
                if (wechatTagIds.size()>0){
                    LambdaQueryWrapper<WechatTagInfo> tagInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
                    tagInfoLambdaQueryWrapper.in(WechatTagInfo::getTagId,wechatTagIds);
                    List<WechatTagInfo> wechatTagInfos = wechatTagInfoMapper.selectList(tagInfoLambdaQueryWrapper);
                    Map<String, String> collect1 = wechatTagInfos.stream().collect(Collectors.toMap(WechatTagInfo::getTagId, obj -> obj.getTagName()));
                    wechatTagMap.putAll(collect1);
                }
            }


        }
        return iPage.convert(x -> {
            CustomerSalesmanInfoVo vo = new CustomerSalesmanInfoVo();
            BeanUtil.copyProperties(x, vo);
            if (!ObjectUtils.isEmpty(x.getWechatCustomerId())){
                vo.setCustomerMatchingProducts(cmpMap.get(x.getWechatCustomerId().longValue()));
            }
            //系统标签
            List<Long> tagIds = customerTagMap.get(x.getCustomerId().longValue());
            if (!ObjectUtils.isEmpty(tagIds)&&!tagIds.isEmpty()){
                List<String> sysTags=new ArrayList<>();
                for (Long tagId : tagIds) {
                    String tagName = tagMap.get(tagId);
                    if (!ObjectUtils.isEmpty(tagName)){
                        sysTags.add(tagName);
                    }
                }
                vo.setSysTags(sysTags);
            }
            //企微标签
            if (!ObjectUtils.isEmpty(x.getWechatTagIds())){
                List<String> wechatTagIds = JSON.parseArray(x.getWechatTagIds().toString(), String.class);
                List<String> wechatTags=new ArrayList<>();
                for (String wechatTagId : wechatTagIds) {
                    String wechatTagName = wechatTagMap.get(wechatTagId);
                    if (StringUtils.isNotBlank(wechatTagName)){
                        wechatTags.add(wechatTagName);
                    }
                }
                vo.setWechatTags(wechatTags);
            }
            //手机号脱敏
//            if(!ObjectUtils.isEmpty(x.getPhone())){
//                if (x.getPhone().length() >= 7 && x.getPhone().length() < 11){
//                    String prefix = x.getPhone().substring(0,2);
//                    String suffix = x.getPhone().substring(6);
//                    String middle = "*".repeat(4);
//                    x.setPhone(prefix + middle + suffix);
//                }
//                if (x.getPhone().length() >= 11){
//                    String prefix = x.getPhone().substring(0,3);
//                    String suffix = x.getPhone().substring(8);
//                    String middle = "*".repeat(5);
//                    vo.setPhone(prefix + middle + suffix);
//                }
//            }

            return vo;
        });
    }


    @Override
    public IPage<CustomerWechatInfoVo> customerWechatPageQuery(CustomerWechatPageDto command) {
        Page<CustomerWechatInfoVo> Page = new Page<>(command.getPageNum(), command.getPageSize());
        IPage<CustomerWechatInfoVo> iPage = wechatFollowCustomerService.customerWechatPageQuery(Page, command);
        List<CustomerWechatInfoVo> records = iPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            return iPage;
        }
        Set<Integer> customerIds = records.stream().map(CustomerWechatInfoVo::getCustomerId).collect(Collectors.toSet());
        List<Integer> wechatCustomerIds = records.stream().map(CustomerWechatInfoVo::getWechatCustomerId).toList();
        Map<Long,List<CustomerMatchingProduct>> cmpMap=new HashMap<>();
        if (!ObjectUtils.isEmpty(wechatCustomerIds)&&wechatCustomerIds.size()>0){
            //客户分配产品
            LambdaQueryWrapper<CustomerMatchingProduct> matchingProductLambdaQueryWrapper=new LambdaQueryWrapper<>();
            matchingProductLambdaQueryWrapper.in(CustomerMatchingProduct::getWechatCustomerId,wechatCustomerIds);
            List<CustomerMatchingProduct> matchingProducts = customerMatchingProductService.list(matchingProductLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(matchingProducts)){
                Set<Long> mpIds = matchingProducts.stream().map(i -> i.getMatchingProductId()).collect(Collectors.toSet());
                List<MatchingProduct> matchingProductList = matchingProductService.listByIds(mpIds);
                Map<Integer, String> mpMap = matchingProductList.stream().collect(Collectors.toMap(MatchingProduct::getId, obj -> obj.getName()));
                for (CustomerMatchingProduct matchingProduct : matchingProducts) {
                    List<CustomerMatchingProduct> wechatCustomerMatchingProducts = cmpMap.get(matchingProduct.getWechatCustomerId());
                    if (ObjectUtils.isEmpty(wechatCustomerMatchingProducts)){
                        wechatCustomerMatchingProducts = new ArrayList<>();
                        cmpMap.put(matchingProduct.getWechatCustomerId(),wechatCustomerMatchingProducts);
                    }
                    if(StringUtils.isNotBlank(mpMap.get(matchingProduct.getMatchingProductId().intValue()))){
                        matchingProduct.setMatchingProductName(mpMap.get(matchingProduct.getMatchingProductId().intValue()));
                        wechatCustomerMatchingProducts.add(matchingProduct);
                    }
                }
            }
        }
        //系统标签
        Map<Long,List<Long>> customerTagMap=new HashMap<>();
        Map<Long, String> tagMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(customerIds)){
            LambdaQueryWrapper<CustomerTag> customerTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            customerTagLambdaQueryWrapper.in(CustomerTag::getCustomerInfoId,customerIds);
            List<CustomerTag> customerTagList = customerTagService.list(customerTagLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(customerTagList) && !customerTagList.isEmpty()){
                for (CustomerTag customerTag : customerTagList) {
                    List<Long> tagIdList = customerTagMap.get(customerTag.getCustomerInfoId());
                    if (ObjectUtils.isEmpty(tagIdList)){
                        tagIdList=new ArrayList<>();
                    }
                    tagIdList.add(customerTag.getTagInfoId());
                    customerTagMap.put(customerTag.getCustomerInfoId(),tagIdList);
                }
                Set<Long> tagInfoIds = customerTagList.stream().map(i -> i.getTagInfoId()).collect(Collectors.toSet());
                List<TagInfo> tagInfoList = tagInfoService.listByIds(tagInfoIds);
                Map<Long, String> tagNameMap = tagInfoList.stream().collect(Collectors.toMap(TagInfo::getId, obj -> obj.getName()));
                tagMap.putAll(tagNameMap);
            }
        }

        //企微标签
        Set<String> wechatTagIds=new HashSet<>();
        Map<String, String> wechatTagMap = new HashMap<>();
        for (CustomerWechatInfoVo record : records) {
            if (!ObjectUtils.isEmpty(record.getWechatTagIds())){
                wechatTagIds.addAll(JSON.parseArray(record.getWechatTagIds().toString(), String.class));
            }
        }
        if (wechatTagIds.size()>0){
            LambdaQueryWrapper<WechatTagInfo> tagInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
            tagInfoLambdaQueryWrapper.in(WechatTagInfo::getTagId,wechatTagIds);
            List<WechatTagInfo> wechatTagInfos = wechatTagInfoMapper.selectList(tagInfoLambdaQueryWrapper);
            Map<String, String> wechatTagNameMap = wechatTagInfos.stream().collect(Collectors.toMap(WechatTagInfo::getTagId, obj -> obj.getTagName()));
            wechatTagMap.putAll(wechatTagNameMap);
        }


        return iPage.convert(x -> {
            x.setAddWay(x.getAddWay());
            if(Objects.nonNull(x.getWechatCreatetime())){
                long wechatAddTime = x.getWechatCreatetime() * 1000;
                x.setWechatAddTime(new Date(wechatAddTime));
            }
            if(Objects.nonNull(x.getRunTime())) {
                long runTime = x.getRunTime() * 1000;
                x.setRunDate(new Date(runTime));
            }

            // 获取date类型的当前时间
            Date currentDate = new Date();
            Date followTime = x.getLastFollowTime();
            if (ObjectUtil.isNotEmpty(followTime)) {
                // 计算时间间隔 绝对值
                long timeDifferenceInMillis = Math.abs(currentDate.getTime() - followTime.getTime());
                // 将毫秒转换为小时
                long hours = timeDifferenceInMillis / (1000 * 60 * 60);
                if (hours <= 24 && hours > 0) {
                    x.setIntervalDate(hours + "小时");
                } else if (hours > 0) {
                    long day = hours / 24; // 商
                    long hour = hours % 24; // 取余数
                    x.setIntervalDate(day + "天" + "零" + hour + "小时");
                }
            }
            if (!ObjectUtils.isEmpty(x.getWechatCustomerId())){
                x.setCustomerMatchingProducts(cmpMap.get(x.getWechatCustomerId().longValue()));
            }

            //系统标签
            if (!ObjectUtils.isEmpty(x.getCustomerId())){
                List<Long> tagIds = customerTagMap.get(x.getCustomerId().longValue());
                //boolean xtfalg=false;
                if (!ObjectUtils.isEmpty(tagIds)&&!tagIds.isEmpty()){
                    List<String> sysTags=new ArrayList<>();
                    for (Long tagId : tagIds) {
                        String tagName = tagMap.get(tagId);
                        if (!ObjectUtils.isEmpty(tagName)){
                            sysTags.add(tagName);
                        }
                    }
                    x.setSysTags(sysTags);
                }
            }

            //企微标签
            if (!ObjectUtils.isEmpty(x.getWechatTagIds())){
                //boolean qvfalg=false;
                List<String> wechatTagIdList = JSON.parseArray(x.getWechatTagIds().toString(), String.class);
                if (!ObjectUtils.isEmpty(wechatTagIdList)&&!wechatTagIdList.isEmpty()){
                    List<String> wechatTags=new ArrayList<>();
                    for (String wechatTagId : wechatTagIdList) {
                        String wechatTagName = wechatTagMap.get(wechatTagId);
                        if (StringUtils.isNotBlank(wechatTagName)){
                            wechatTags.add(wechatTagName);
                        }
                    }
                    x.setWechatTags(wechatTags);
                }
            }

            if(command.getIsSalesmanUser()){
                //微信手机号脱敏
                if (!ObjectUtils.isEmpty(x.getWechatRemarkMobiles())){
                    List<String> wechatRemarkMobiles = JSON.parseArray(x.getWechatRemarkMobiles().toString(), String.class);
                    List<String> reselutMobiles=new ArrayList<>();
                    for (String wechatRemarkMobile : wechatRemarkMobiles) {
                        if (wechatRemarkMobile.length() >= 7 && wechatRemarkMobile.length() < 11){
                            String prefix = wechatRemarkMobile.substring(0,2);
                            String suffix = wechatRemarkMobile.substring(6);
                            String middle = "*".repeat(4);
                            reselutMobiles.add(prefix + middle + suffix);
                        }
                        if (wechatRemarkMobile.length() >= 11){
                            String prefix = wechatRemarkMobile.substring(0,3);
                            String suffix = wechatRemarkMobile.substring(8);
                            String middle = "*".repeat(5);
                            reselutMobiles.add(prefix + middle + suffix);
                        }
                    }
                    x.setWechatRemarkMobiles(JSON.toJSONString(reselutMobiles));
                }
                //用户手机号脱敏
//                if(!ObjectUtils.isEmpty(x.getPhone())){
//                    if (x.getPhone().length() >= 7 && x.getPhone().length() < 11){
//                        String prefix = x.getPhone().substring(0,2);
//                        String suffix = x.getPhone().substring(6);
//                        String middle = "*".repeat(4);
//                        x.setPhone(prefix + middle + suffix);
//                    }
//                    if (x.getPhone().length() >= 11){
//                        String prefix = x.getPhone().substring(0,3);
//                        String suffix = x.getPhone().substring(8);
//                        String middle = "*".repeat(5);
//                        x.setPhone(prefix + middle + suffix);
//                    }
//                }
            }
            return x;
        });
    }

    @Override
    public OrderUserApplyDetailDTO customerInfoDetail(Long customerId,Long wechatCustomerId) {
        CustomerInfoDetail detail = customerInfoDetailService.getOne(new LambdaQueryWrapper<CustomerInfoDetail>().eq(CustomerInfoDetail::getCustomerInfoId, customerId));

        CustomerInfo info = baseMapper.getCustomerInfo(customerId);
        CustomerInfoDetailVo detailVo = new CustomerInfoDetailVo();
        BeanUtil.copyProperties(detail, detailVo);
        if(Objects.nonNull(info)){
            detailVo.setName(info.getName());
            detailVo.setPhone(info.getPhone());
        }
        // 数据转换
        OrderUserApplyDetailDTO userApplyDetail = getUserApplyDetail(detailVo);
        userApplyDetail.setUserName(detailVo.getName());
        userApplyDetail.setUserPhone(detailVo.getPhone());
        if (!ObjectUtils.isEmpty(wechatCustomerId)){
            WechatFollowCustomer followCustomer = wechatFollowCustomerService.getById(wechatCustomerId);
            BeanUtil.copyProperties(followCustomer,userApplyDetail);
            if (!ObjectUtils.isEmpty(followCustomer)&&!ObjectUtils.isEmpty(followCustomer.getWechatTagIds())){
                List<String> TagInfoIds = JSON.parseArray((String) followCustomer.getWechatTagIds(), String.class);
                List<WechatTagInfo> tagList = wechatTagInfoMapper.selectList(new LambdaQueryWrapper<WechatTagInfo>().in(WechatTagInfo::getTagId, TagInfoIds));
                userApplyDetail.setWechatTagInfoList(tagList);
            }
        }
        LambdaQueryWrapper<CustomerTag> tagLambdaQueryWrapper=new LambdaQueryWrapper<>();
        tagLambdaQueryWrapper.eq(CustomerTag::getCustomerInfoId,customerId);
        List<CustomerTag> customerTags = customerTagService.list(tagLambdaQueryWrapper);
        List<Long> tagIds = customerTags.stream().map(i -> i.getTagInfoId()).toList();
        if (CollUtil.isNotEmpty(tagIds)) {
            List<TagInfo> infos = tagInfoService.list(new LambdaQueryWrapper<TagInfo>().in(TagInfo::getId, tagIds));
            userApplyDetail.setTagInfoList(infos);
        }

        return userApplyDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean operationCustomerInfo(OperationCustomerInfoDto dto) {
        if (!ObjectUtils.isEmpty(dto.getTelephonerStatus()) && dto.getTelephonerStatus()==3) {
            if (ObjectUtils.isEmpty(dto.getTelephonerToTime())){
                throw new BusinessException("添加状态,必须填写业务员添加时间");
            }
        }
        AdminUser adminUser = adminUserMapper.getAdminUser(dto.getCreaterId().intValue());
        CustomerInfo info = baseMapper.getCustomerInfo(dto.getId().longValue());
        if (!ObjectUtils.isEmpty(dto.getPhone()) && !dto.getPhone().equals("")){
            if (ObjectUtils.isEmpty(info.getPhone()) || !dto.getPhone().equals(info.getPhone())){
                if (info.getIsWechat()==1){
                    throw new BusinessException("该客户已经绑定企微客户,请勿修改手机号");
                }
                //绑定企微
                List<String> list = Arrays.asList(dto.getPhone());
                LambdaQueryWrapper<WechatFollowCustomer> followCustomerLambdaQueryWrapper=new LambdaQueryWrapper<>();
                followCustomerLambdaQueryWrapper.eq(WechatFollowCustomer::getCustomerNo,"-1")
                        .eq(WechatFollowCustomer::getTeamId,info.getTeamId())
                        .apply("JSON_CONTAINS(wechat_remark_mobiles, {0})", JSON.toJSONString(list))
                        .orderByDesc(WechatFollowCustomer::getId).last("limit 1");
                WechatFollowCustomer wechatFollowCustomer = wechatFollowCustomerService.getOne(followCustomerLambdaQueryWrapper);
                if (!ObjectUtils.isEmpty(wechatFollowCustomer)){
                    wechatFollowCustomer.setCustomerNo(info.getCustomerNo());
                    wechatFollowCustomerService.updateById(wechatFollowCustomer);
                    info.setIsWechat(1);
                    info.setSalesmanId(wechatFollowCustomer.getSysUserId());
                    info.setSalesmanTime(new Date());
                    info.setSeasType(0);
                }
            }

        }

        BeanUtil.copyProperties(dto, info,"isWechat","salesmanId","salesmanTime","seasType");
        if (!ObjectUtils.isEmpty(info.getPhone()) && info.getPhone().equals("")){
            info.setPhone(null);
        }
        if (!ObjectUtils.isEmpty(info.getName()) && info.getName().equals("")){
            info.setName(null);
        }
        info.setCtDescribe(dto.getDescribe());
        List<CustomerTag> list = new ArrayList<>();
        try {
            if (CollUtil.isNotEmpty(dto.getTagIds())) {
                // 先把原来的标签全删了
                LambdaQueryWrapper<CustomerTag> tagQueryWrapper=new LambdaQueryWrapper<>();
                tagQueryWrapper.select(CustomerTag::getTagInfoId).eq(CustomerTag::getCustomerInfoId,dto.getId());
                List<CustomerTag> customerTags = customerTagService.list(tagQueryWrapper);

                if (!ObjectUtils.isEmpty(customerTags) && customerTags.size()>0){
                    List<Long> tagIds = customerTags.stream().map(i -> i.getTagInfoId()).toList();
                    boolean updateTagFlag = false;
                    if (tagIds.size() != dto.getTagIds().size()){
                        updateTagFlag = true;
                    }else {
                        List<Long> updateTagIds = dto.getTagIds().stream().filter(i -> !tagIds.contains(i)).toList();
                        if (!updateTagIds.isEmpty()){
                            updateTagFlag = true;
                        }
                    }
                    if (updateTagFlag){
                        //记录修改标签
                        savaCustomerTagLog(dto, info, adminUser,2);
                    }
                    customerTagMapper.delete(new LambdaQueryWrapper<CustomerTag>().eq(CustomerTag::getCustomerInfoId, dto.getId()));
                }else {
                    //记录新增标签
                    savaCustomerTagLog(dto, info, adminUser,1);
                }
                // 新增客户标签
                if (dto.getTagIds().get(0) != -1){
                    for (Long tagId : dto.getTagIds()) {
                        CustomerTag customerTag = new CustomerTag();
                        customerTag.setCustomerInfoId(dto.getId().longValue());
                        customerTag.setTagInfoId(tagId);
                        list.add(customerTag);
                    }
                    customerTagService.saveBatch(list);
                }
            }
            //用于判断是否进入公海池
            if (!ObjectUtils.isEmpty(info.getTelephonerStatus())
                    || !ObjectUtils.isEmpty(info.getCallCount())
                    || !ObjectUtils.isEmpty(info.getTelephonerToTime())
                    || (!ObjectUtils.isEmpty(info.getPhone()) && !info.getPhone().equals(""))
                    || (!ObjectUtils.isEmpty(info.getName()) && !info.getName().equals(""))){
                info.setLastFollowTime(new Date());
            }

            this.updateById(info);
            List<OperationCustomerInfoDto.CustomerMatchingProductDto> matchingProductDtoList = dto.getMatchingProductDtoList();
            if (!ObjectUtils.isEmpty(matchingProductDtoList)){
                List<CustomerMatchingProduct> matchingProducts=new ArrayList<>();
                LambdaQueryWrapper<CustomerMatchingProduct> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(CustomerMatchingProduct::getCustomerId,info.getId());
                customerMatchingProductService.remove(queryWrapper);
                for (OperationCustomerInfoDto.CustomerMatchingProductDto customerMatchingProductDto : matchingProductDtoList) {
                    CustomerMatchingProduct customerMatchingProduct=new CustomerMatchingProduct();
                    BeanUtils.copyProperties(customerMatchingProductDto,customerMatchingProduct);
                    customerMatchingProduct.setCustomerId(info.getId());
                    matchingProducts.add(customerMatchingProduct);
                }
                if (!matchingProducts.isEmpty()){
                    customerMatchingProductService.saveBatch(matchingProducts);
                }
            }
        } catch (Exception e) {
            throw new BusinessException("操作客户信息异常:" + e.getMessage());
        }
        return true;
    }

    @Override
    public Boolean operationWechatCustomerInfo(OperationWechatCustomerInfoDto dto) {
        WechatFollowCustomer followCustomer = wechatFollowCustomerService.getById(dto.getWechatCustomerId());
        if (ObjectUtils.isEmpty(followCustomer)){
            throw new BusinessException("未找到资源");
        }
        AdminUser adminUser = adminUserMapper.getAdminUser(dto.getUserId().intValue());
        LambdaUpdateWrapper<WechatFollowCustomer> followCustomerLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        followCustomerLambdaUpdateWrapper.eq(WechatFollowCustomer::getId,dto.getWechatCustomerId())
                .set(!ObjectUtils.isEmpty(dto.getFollowStatus()),WechatFollowCustomer::getFollowStatus,dto.getFollowStatus())
                .set(!ObjectUtils.isEmpty(dto.getMakeOrderTime()),WechatFollowCustomer::getMakeOrderTime,dto.getMakeOrderTime());
        wechatFollowCustomerService.update(followCustomerLambdaUpdateWrapper);
        //修改企微客户关联产品信息
        List<OperationCustomerInfoDto.CustomerMatchingProductDto> matchingProductDtoList = dto.getMatchingProductDtoList();
        if (!ObjectUtils.isEmpty(matchingProductDtoList) && matchingProductDtoList.size()>0){
            List<CustomerMatchingProduct> matchingProducts=new ArrayList<>();
            LambdaQueryWrapper<CustomerMatchingProduct> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(CustomerMatchingProduct::getWechatCustomerId,dto.getWechatCustomerId());
            List<CustomerMatchingProduct> agoMatchingProducts = customerMatchingProductService.list(queryWrapper);
            if (!agoMatchingProducts.isEmpty()){
                //修改产品日志
                updateProductLog(dto, adminUser,2);
                customerMatchingProductService.remove(queryWrapper);
            }else {
                //新增产品日志
                updateProductLog(dto, adminUser,1);
            }

            CustomerInfo customerInfo = null;
            if (!ObjectUtils.isEmpty(followCustomer.getCustomerNo())){
                LambdaQueryWrapper<CustomerInfo> customerInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
                customerInfoLambdaQueryWrapper.eq(CustomerInfo::getCustomerNo,followCustomer.getCustomerNo());
                customerInfo = this.getOne(customerInfoLambdaQueryWrapper);
            }
            for (OperationCustomerInfoDto.CustomerMatchingProductDto customerMatchingProductDto : matchingProductDtoList) {
                CustomerMatchingProduct customerMatchingProduct=new CustomerMatchingProduct();
                BeanUtils.copyProperties(customerMatchingProductDto,customerMatchingProduct);
                customerMatchingProduct.setWechatCustomerId(dto.getWechatCustomerId());
                customerMatchingProduct.setUserId(dto.getUserId().intValue());
                if (!ObjectUtils.isEmpty(customerInfo)){
                    customerMatchingProduct.setCustomerId(customerInfo.getId());
                }
                matchingProducts.add(customerMatchingProduct);
            }
            if (!matchingProducts.isEmpty()){
                customerMatchingProductService.saveBatch(matchingProducts);
            }
        }
        return null;
    }

    private void updateProductLog(OperationWechatCustomerInfoDto dto, AdminUser adminUser,Integer saveOrUpdate) {
        StringBuilder logData = new StringBuilder();
        List<OperationCustomerInfoDto.CustomerMatchingProductDto> matchingProductDtoList = dto.getMatchingProductDtoList();
        List<Long> matchingProductIds = matchingProductDtoList.stream().map(i -> i.getMatchingProductId()).toList();
        Map<Long, OperationCustomerInfoDto.CustomerMatchingProductDto> productDtoMap = matchingProductDtoList.stream().collect(Collectors.toMap(OperationCustomerInfoDto.CustomerMatchingProductDto::getMatchingProductId, obj -> obj));
        List<MatchingProduct> matchingProductList = matchingProductService.listByIds(matchingProductIds);
        for (MatchingProduct matchingProduct : matchingProductList) {
            OperationCustomerInfoDto.CustomerMatchingProductDto customerMatchingProductDto = productDtoMap.get(matchingProduct.getId().longValue());
            if (StringUtils.isBlank(logData)){
                logData.append(matchingProduct.getName()+",数量:"+customerMatchingProductDto.getCount());
                if (!ObjectUtils.isEmpty(customerMatchingProductDto.getStatus())){
                    switch (customerMatchingProductDto.getStatus()) {
                        case -1 -> logData.append(",状态:失败");
                        case 0 -> logData.append(",状态:审核中");
                        case 1 -> logData.append(",状态:失败");
                    }
                }
            }else {
                logData.append(";],[ "+matchingProduct.getName()+",数量:"+customerMatchingProductDto.getCount());
                if (!ObjectUtils.isEmpty(customerMatchingProductDto.getStatus())){
                    switch (customerMatchingProductDto.getStatus()) {
                        case -1 -> logData.append(",状态:失败");
                        case 0 -> logData.append(",状态:审核中");
                        case 1 -> logData.append(",状态:失败");
                    }
                }
            }

        }
        //新增产品日志
        CustomerOperationLog customerOperationLog=new CustomerOperationLog();
        customerOperationLog.setCustomerWechatId(dto.getWechatCustomerId());
        customerOperationLog.setType(2);
        if (saveOrUpdate==1){
            customerOperationLog.setLogData("添加产品:["+logData+"]");
        }else {
            customerOperationLog.setLogData("修改产品:["+logData+"]");
        }
        customerOperationLog.setCreateTime(new Date());
        customerOperationLog.setCreator(adminUser.getNickname());
        customerOperationLogService.save(customerOperationLog);
    }

    private void savaCustomerTagLog(OperationCustomerInfoDto dto, CustomerInfo info, AdminUser adminUser,Integer saveOrUpdate) {
        List<TagInfo> tagInfoList = tagInfoService.listByIds(dto.getTagIds());
        StringBuilder logData = new StringBuilder();
        for (TagInfo tagInfo : tagInfoList) {
            if (StringUtils.isEmpty(logData)){
                logData.append(tagInfo.getName());
            }else {
                logData.append(","+tagInfo.getName());
            }
        }
        CustomerOperationLog customerOperationLog=new CustomerOperationLog();
        customerOperationLog.setCustomerInfoId(info.getId());
        customerOperationLog.setCustomerNo(info.getCustomerNo());
        customerOperationLog.setType(1);
        if (saveOrUpdate==1){
            customerOperationLog.setLogData("添加标签:["+logData+"]");
        }else {
            customerOperationLog.setLogData("修改标签:["+logData+"]");
        }
        customerOperationLog.setCreateTime(new Date());
        customerOperationLog.setCreator(adminUser.getNickname());
        customerOperationLogService.save(customerOperationLog);
    }

    @Override
    public CustomerOperationInfoVo CustomerOperationInfo(Long customerId) {
        CustomerInfo info = baseMapper.selectById(customerId);
        CustomerOperationInfoVo vo = new CustomerOperationInfoVo();
        BeanUtil.copyProperties(info, vo);
        // 客户标签
        List<Long> tagIds = customerTagMapper.selectList(new LambdaQueryWrapper<CustomerTag>().eq(CustomerTag::getCustomerInfoId, customerId)).stream().map(CustomerTag::getTagInfoId).toList();

        if (CollUtil.isNotEmpty(tagIds)) {
            List<TagInfo> infos = tagInfoService.list(new LambdaQueryWrapper<TagInfo>().in(TagInfo::getId, tagIds));
            vo.setTagInfoId(infos);
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean reDistribution(operationDistributionDto dto,CustomerInfo customerInfo) {
        //该话务员是否在该业务员名下
//        if (!ObjectUtils.isEmpty(dto.getSalesmanId()) && dto.getSalesmanId()!=-1){
//            if (!ObjectUtils.isEmpty(dto.getTelephoneId()) && dto.getTelephoneId()!=-1){
//                LambdaQueryWrapper<CustomerShipAllocation> allocationLambdaQueryWrapper=new LambdaQueryWrapper<>();
//                allocationLambdaQueryWrapper.eq(CustomerShipAllocation::getSalesmanId,dto.getSalesmanId())
//                        .eq(CustomerShipAllocation::getTelephoneId,dto.getTelephoneId())
//                        .eq(CustomerShipAllocation::getTeamId,dto.getTeamId());
//                CustomerShipAllocation customerShipAllocation = customerShipAllocationService.getOne(allocationLambdaQueryWrapper);
//                if (ObjectUtils.isEmpty(customerShipAllocation)){
//                    throw new BusinessException("该话务员不在该业务员下");
//                }
//            }
//        }

        AdminUser adminUser = adminUserMapper.getAdminUser(dto.getOperator());
        if (ObjectUtils.isEmpty(dto.getTeamId())){
            customerInfo.setTeamId(-1);
        }else {
            customerInfo.setTeamId(dto.getTeamId());
        }
//        if (ObjectUtils.isEmpty(dto.getSalesmanId())){
//            customerInfo.setSalesmanId(-1);
//        }else {
//            customerInfo.setSalesmanId(dto.getSalesmanId());
//            customerInfo.setSalesmanTime(new Date());
//        }
        if (ObjectUtils.isEmpty(dto.getTelephoneId())){
            customerInfo.setTelephonerId(-1);
        }else {
            customerInfo.setTelephonerId(dto.getTelephoneId());
            customerInfo.setTelephonerTime(new Date());
            customerInfo.setSeasType(0);
            //保存分配日志
            CustomerTelephonerLog customerTelephonerLog=new CustomerTelephonerLog();
            customerTelephonerLog.setCustomerInfoId(customerInfo.getId());
            customerTelephonerLog.setUserId(customerInfo.getTelephonerId().longValue());
            customerTelephonerLog.setType(1);
            customerTelephonerLog.setCreateTime(customerInfo.getTelephonerTime());
            customerTelephonerLogService.save(customerTelephonerLog);
        }
        customerInfo.setEditor(adminUser.getNickname());
        return this.updateById(customerInfo);
    }

    @Override
    public Boolean batchReassign(BatchOperationDistributionDto dto, List<CustomerInfo> customerInfos) {
        //该话务员是否在该业务员名下
//        if (!ObjectUtils.isEmpty(dto.getSalesmanId()) && dto.getSalesmanId()!=-1){
//            if (!ObjectUtils.isEmpty(dto.getTelephoneId()) && dto.getTelephoneId()!=-1){
//                LambdaQueryWrapper<CustomerShipAllocation> allocationLambdaQueryWrapper=new LambdaQueryWrapper<>();
//                allocationLambdaQueryWrapper.eq(CustomerShipAllocation::getSalesmanId,dto.getSalesmanId())
//                        .eq(CustomerShipAllocation::getTelephoneId,dto.getTelephoneId())
//                        .eq(CustomerShipAllocation::getTeamId,dto.getTeamId());
//                CustomerShipAllocation customerShipAllocation = customerShipAllocationService.getOne(allocationLambdaQueryWrapper);
//                if (ObjectUtils.isEmpty(customerShipAllocation)){
//                    throw new BusinessException("该话务员不在该业务员下");
//                }
//            }
//        }
        AdminUser adminUser = adminUserMapper.getAdminUser(dto.getOperator());
        for (CustomerInfo customerInfo : customerInfos) {
            if (ObjectUtils.isEmpty(dto.getTeamId())){
                customerInfo.setTeamId(-1);
            }else {
                customerInfo.setTeamId(dto.getTeamId());
            }
//            if (ObjectUtils.isEmpty(dto.getSalesmanId())){
//                customerInfo.setSalesmanId(-1);
//            }else {
//                customerInfo.setSalesmanId(dto.getSalesmanId());
//                customerInfo.setSalesmanTime(new Date());
//            }
            if (ObjectUtils.isEmpty(dto.getTelephoneId())){
                customerInfo.setTelephonerId(-1);
            }else {
                customerInfo.setTelephonerId(dto.getTelephoneId());
                customerInfo.setTelephonerTime(new Date());
                customerInfo.setSeasType(0);
                //保存分配日志
                CustomerTelephonerLog customerTelephonerLog=new CustomerTelephonerLog();
                customerTelephonerLog.setCustomerInfoId(customerInfo.getId());
                customerTelephonerLog.setUserId(customerInfo.getTelephonerId().longValue());
                customerTelephonerLog.setType(1);
                customerTelephonerLog.setCreateTime(customerInfo.getTelephonerTime());
                customerTelephonerLogService.save(customerTelephonerLog);
            }
            customerInfo.setEditor(adminUser.getNickname());
        }
        return this.updateBatchById(customerInfos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean relieveDistribution(Long customerId,Long userId) {
        CustomerInfo customerInfo = this.getById(customerId);
        if (ObjectUtils.isEmpty(customerInfo)){
            throw new BusinessException("没有该客户");
        }
        LambdaQueryWrapper<WechatFollowCustomer> followCustomerLambdaQueryWrapper=new LambdaQueryWrapper<>();
        followCustomerLambdaQueryWrapper.eq(WechatFollowCustomer::getCustomerNo,customerInfo.getCustomerNo());
        long count = wechatFollowCustomerService.count(followCustomerLambdaQueryWrapper);
        if (count>0){
            throw new BusinessException("该客户关联企微客户 请勿解除分配");
        }

        AdminUser adminUser = adminUserMapper.getAdminUser(userId.intValue());
        CustomerInfo info = new CustomerInfo();
        info.setSalesmanId(-1);
        info.setTelephonerId(-1);
        info.setId(customerId);
        info.setEditor(adminUser.getNickname());
        return this.updateById(info);
    }

    @Override
    public newCustomerCountVo newCustomerCount() {
        LocalDateTime endTime = LocalDateTime.now();
        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 获取这一天的开始时间（即当天的 00:00:00）
        LocalDateTime starTime = today.atStartOfDay();
        // 获取新增客户数
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<CustomerInfo>().between(CustomerInfo::getCreateTime, starTime, endTime));
        // 获取新增标记数
        Long signCount = baseMapper.signCount();
        newCustomerCountVo vo = new newCustomerCountVo();
        vo.setNewCount(count);
        vo.setSignCount(signCount);
        return vo;
    }

    @Override
    public List<CustomerOperationLog> getOperationLogByCustomerId(Long customerId) {
        CustomerInfo customerInfo = this.getById(customerId);
        if (ObjectUtils.isEmpty(customerInfo)){
            throw new BusinessException("未找到资源");
        }
        LambdaQueryWrapper<WechatFollowCustomer> followCustomerLambdaQueryWrapper=new LambdaQueryWrapper<>();
        followCustomerLambdaQueryWrapper.eq(WechatFollowCustomer::getCustomerNo,customerInfo.getCustomerNo());
        WechatFollowCustomer wechatFollowCustomer = wechatFollowCustomerService.getOne(followCustomerLambdaQueryWrapper);
        LambdaQueryWrapper<CustomerOperationLog> operationLogLambdaQueryWrapper=new LambdaQueryWrapper<>();
        operationLogLambdaQueryWrapper.eq(CustomerOperationLog::getCustomerInfoId,customerId);
        if (!ObjectUtils.isEmpty(wechatFollowCustomer)){
            operationLogLambdaQueryWrapper.or()
                    .eq(CustomerOperationLog::getCustomerWechatId,wechatFollowCustomer.getId());
        }
        operationLogLambdaQueryWrapper.orderByDesc(CustomerOperationLog::getId);
        return customerOperationLogService.list(operationLogLambdaQueryWrapper);
    }

    @Override
    public List<CustomerOperationLog> getOperationLogByWechatCustomerId(Long wechatCustomerId) {
        WechatFollowCustomer followCustomer = wechatFollowCustomerService.getById(wechatCustomerId);
        if (ObjectUtils.isEmpty(followCustomer)){
            throw new BusinessException("未找到资源");
        }
        LambdaQueryWrapper<CustomerOperationLog> operationLogLambdaQueryWrapper=new LambdaQueryWrapper<>();
        operationLogLambdaQueryWrapper.eq(CustomerOperationLog::getCustomerWechatId,wechatCustomerId);
        if (!ObjectUtils.isEmpty(followCustomer.getCustomerNo()) && !followCustomer.getCustomerNo().equals("-1")){
            operationLogLambdaQueryWrapper.or()
                    .eq(CustomerOperationLog::getCustomerNo,followCustomer.getCustomerNo());
        }
        operationLogLambdaQueryWrapper.orderByDesc(CustomerOperationLog::getId);
        return customerOperationLogService.list(operationLogLambdaQueryWrapper);
    }

    private void extracted(List<Integer> customerIds, IPage<CustomerCommonVo> iPage) {
        if (CollUtil.isNotEmpty(customerIds)) {
            List<Long> tagIds = customerTagMapper.selectList(new LambdaQueryWrapper<CustomerTag>().in(CustomerTag::getCustomerInfoId, customerIds))
                    .stream().map(CustomerTag::getTagInfoId).toList();
            Map<Long, List<CustomerTag>> listMap = customerTagMapper.selectList(new LambdaQueryWrapper<CustomerTag>().in(CustomerTag::getCustomerInfoId, customerIds))
                    .stream().collect(Collectors.groupingBy(CustomerTag::getTagInfoId));
            if (CollUtil.isNotEmpty(tagIds)) {
                Map<Long, List<TagInfo>> ListMap = tagInfoService.list(new LambdaQueryWrapper<TagInfo>()
                                .in(TagInfo::getId, tagIds))
                        .stream()
                        .collect(Collectors.groupingBy(TagInfo::getId));
                tagIds.forEach(id -> {
                    List<TagInfo> infos = ListMap.get(id);
                    infos.stream().map(TagInfo::getParentId).collect(Collectors.toSet());
                    List<Long> list = listMap.get(id).stream().map(CustomerTag::getCustomerInfoId).toList();
                    iPage.getRecords().forEach(x -> {
                        list.forEach(cid -> {
                            if (cid.equals(x.getCustomerId().longValue())) {
                                x.setTagInfoId(infos);
                            }
                        });
                    });
                });
            }
        }
    }


    private void wechatTag(List<Long> wechatInfoIds, CustomerCommonVo iPage, CustomerSalesmanInfoVo vo) {
        if (CollUtil.isNotEmpty(wechatInfoIds)) {
            Map<Long, List<WechatTagInfo>> tagMap = wechatTagInfoMapper.selectList(new LambdaQueryWrapper<WechatTagInfo>()
                    .in(WechatTagInfo::getWechatInfoId, wechatInfoIds)).stream().collect(Collectors.groupingBy(WechatTagInfo::getWechatInfoId));
            wechatInfoIds.forEach(x -> {
                List<WechatTagInfo> infos = tagMap.get(x);
                if (iPage.getWechatInfoId().equals(x)) {
                    vo.setWeChatTagInfo(infos);
                }
            });
        }


    }


    // 查询所有的客户字段
    private IPage<CustomerCommonVo> listAllCustomerInfo(CustomerCommonPageDto command) {
        Page<CustomerCommonVo> Page = new Page<>(command.getPageNum(), command.getPageSize());
        IPage<CustomerCommonVo> customerCommonVoIPage = baseMapper.listAllCustomerInfo(Page, command);
        List<CustomerCommonVo> records = customerCommonVoIPage.getRecords();
        if (!ObjectUtils.isEmpty(records)){
            Set<Integer> teamIds=new HashSet<>();
            Set<Integer> userIds=new HashSet<>();
            Set<Integer> customerIds=new HashSet<>();
            for (CustomerCommonVo record : records) {
                customerIds.add(record.getCustomerId());
                if (!ObjectUtils.isEmpty(record.getTeamId())){
                    teamIds.add(record.getTeamId());
                }
                if (!ObjectUtils.isEmpty(record.getSalesmanId())){
                    userIds.add(record.getSalesmanId());
                }
                if (!ObjectUtils.isEmpty(record.getTelephoneId())){
                    userIds.add(record.getTelephoneId());
                }
            }
            //团队名
            Map<Integer, String> teamMap = new HashMap<>();
            if (!teamIds.isEmpty()){
                List<Team> teams = teamService.listByIds(teamIds);
                teamMap = teams.stream().collect(Collectors.toMap(Team::getId, Team::getTeamName));
            }
            //业务话务名
            Map<Integer, String> userMap = new HashMap<>();
            if (!userIds.isEmpty()){
                List<AdminUser> adminUsers = adminUserMapper.selectBatchIds(userIds);
                userMap = adminUsers.stream().collect(Collectors.toMap(AdminUser::getId, AdminUser::getNickname));
            }
            //用户详情
            Map<Long, CustomerInfoDetail> customerInfoDetailMap = new HashMap<>();
            if (!customerIds.isEmpty()){
                LambdaQueryWrapper<CustomerInfoDetail> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.in(CustomerInfoDetail::getCustomerInfoId,customerIds);
                List<CustomerInfoDetail> customerInfoDetails = customerInfoDetailService.list(queryWrapper);
                customerInfoDetailMap = customerInfoDetails.stream().collect(Collectors.toMap(CustomerInfoDetail::getCustomerInfoId, obj -> obj));
            }

            for (CustomerCommonVo record : records) {
                CustomerInfoDetail customerInfoDetail = customerInfoDetailMap.get(record.getCustomerId().longValue());
                if (ObjectUtils.isEmpty(customerInfoDetail.getBeOverdue())){
                    customerInfoDetail.setBeOverdue(1);
                }
                record.setCustomerInfoDetail(customerInfoDetail);
                if (!ObjectUtils.isEmpty(record.getTeamId()) && record.getTeamId()!=-1){
                    record.setTeamName(teamMap.get(record.getTeamId()));
                }
                if (!ObjectUtils.isEmpty(record.getSalesmanId()) && record.getSalesmanId()!=-1){
                    record.setSalesmanName(userMap.get(record.getSalesmanId()));
                }
                if (!ObjectUtils.isEmpty(record.getTelephoneId()) && record.getTelephoneId()!=-1){
                    record.setTelephoneName(userMap.get(record.getTelephoneId()));
                }
                record.setAllotCount(customerTelephonerLogService.getAllotCount(record.getCustomerId().longValue(),1));
            }
        }
        return customerCommonVoIPage;
    }

    private OrderUserApplyDetailDTO getUserApplyDetail(CustomerInfoDetailVo result) {
        if (Objects.isNull(result)) {
            return null;
        }
        OrderUserApplyDetailDTO dto = orderAssembler.toCustomerInfoDetailVo(result);
        dto.setAccumulationFund("有");
        if (AccumulationFundLevelEnum.NO_ACCUMULATION_FUND.getValue().equals(result.getAccumulationFundLevel())) {
            dto.setAccumulationFund("无");
        }
        dto.setSocialSecurity("有");
        if (SocialSecurityLevelEnum.NO_SOCIAL_SECURITY.getValue().equals(result.getSocialSecurityLevel())) {
            dto.setSocialSecurity("无");
        }
        return dto;
    }


}




